package com.zide.framework.security.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.zide.common.constant.Constants;
import com.zide.common.core.domain.model.LoginUser;
import com.zide.common.core.domain.model.MemberLoginUser;
import com.zide.framework.security.utils.MemberUserTokenUtil;
import com.zide.framework.security.utils.SystemUserTokenUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * token过滤器 验证token有效性
 *
 * @author xianying
 */
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private SystemUserTokenUtil systemUserTokenUtil;

    @Autowired
    private MemberUserTokenUtil memberUserTokenUtil;

    @Value("${token.header}")
    private String header;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        // 获取token
        String token = request.getHeader(header);
        if (StrUtil.isNotEmpty(token) && token.startsWith(Constants.TOKEN_SYS_PREFIX)) {
            LoginUser loginUser = systemUserTokenUtil.getLoginUser(request);
            // 判断是否为null
            if(ObjectUtil.isNotNull(loginUser)) {
                // 鉴权，跳转的时候需要访问 /index 页面
                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        } else if (StrUtil.isNotEmpty(token) && token.startsWith(Constants.TOKEN_MEM_PREFIX)) {
            MemberLoginUser loginUser = memberUserTokenUtil.getLoginUser(request);
            if(ObjectUtil.isNotNull(loginUser)) {
                // 鉴权，跳转的时候需要访问 /index 页面
                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                // 将用户信息存储到SecurityContext中，SecurityContext存储到SecurityContextHolder中
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }

        }

        chain.doFilter(request, response);
    }
}
